package com.example.tiantian.contact;

import java.util.ArrayList;
import java.util.List;

import com.example.tiantian.BaseActivity;
import com.example.tiantian.R;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.os.Handler.Callback;
import android.text.Editable;
import android.text.TextWatcher;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

public class ContactActivity extends BaseActivity implements Callback, Runnable, OnClickListener,
        DialogInterface.OnClickListener, OnItemClickListener, TextWatcher {

    public static final String ACTION_CLICK = "click_state";
    public static final int REQUEST_CODE_ADD = 0;
    public static final int REQUEST_CODE_EDIT = 1;
    public static final int REQUEST_CODE_SHOW = 2;
    public static final String REQUEST = "qequest";
    public static final String CONTACTINFO = "contactinfo";

    List<ContactInfo> listAll;
    List<ContactInfo> list;

    ListView contacts;
    GridView menu;// menu键菜单
    EditText search;
    TextView empty;

    DBHelper helper;

    ContactsAdapter contactsAdapter;
    MenuAdapter menuAdapter;

    String[] menuTitles;
    int[] menuIconsID;

    Handler handler;

    ProgressDialog dialogLoading;
    AlertDialog dialogMenu;

    TextView showAll;
    TextView deleteAll;
    TextView closeMenu;

    PopupWindow popup;

    @Override
    protected void init() {
        setContentView(R.layout.activity_contacts);

        list = new ArrayList<ContactInfo>();
        listAll = new ArrayList<ContactInfo>();

        contacts = (ListView) findViewById(R.id.contact_list);
        menu = (GridView) findViewById(R.id.contact_menu);
        search = (EditText) findViewById(R.id.contact_search);
        empty = (TextView) findViewById(R.id.contact_empty);

        helper = DBHelper.getHelper(this);

        menuAdapter = new MenuAdapter();

        handler = new Handler(this);

        dialogLoading = new ProgressDialog(this);
        dialogLoading.setTitle(getString(R.string.contact_info_loading));
        dialogLoading.setIcon(R.drawable.icon);
        dialogLoading.setCancelable(false);

        dialogMenu = buildMenu();

        createAPopup();
    }

    private void createAPopup() {
        popup = new PopupWindow(this);
        popup.showAsDropDown(getCurrentFocus());
    }

    private AlertDialog buildMenu() {
        Builder builder = new Builder(this);
        LinearLayout v = new LinearLayout(this);
        v.setOrientation(LinearLayout.HORIZONTAL);
        v.setPadding(15, 15, 15, 15);

        showAll = new TextView(this);
        showAll.setTextColor(Color.WHITE);
        showAll.setText(getString(R.string.contact_menu_show_all));
        Drawable showAllIcon = getResources().getDrawable(R.drawable.showall);
        Rect bounds = new Rect(0, 0, showAllIcon.getMinimumWidth(), showAllIcon.getMinimumHeight());
        showAllIcon.setBounds(bounds);
        showAll.setCompoundDrawables(null, showAllIcon, null, null);
        showAll.setCompoundDrawablePadding(5);
        showAll.setTextSize(15);
        showAll.setId(R.drawable.showall);
        showAll.setPadding(20, 0, 20, 0);
        v.addView(showAll);

        deleteAll = new TextView(this);
        deleteAll.setTextColor(Color.WHITE);
        deleteAll.setText(getString(R.string.contact_menu_delete_all));
        Drawable deleteAllIcon = getResources().getDrawable(R.drawable.menu_delete1);
        deleteAllIcon.setBounds(bounds);
        deleteAll.setCompoundDrawables(null, deleteAllIcon, null, null);
        deleteAll.setCompoundDrawablePadding(5);
        deleteAll.setTextSize(15);
        deleteAll.setId(R.drawable.menu_delete1);
        deleteAll.setPadding(20, 0, 20, 0);
        v.addView(deleteAll);

        closeMenu = new TextView(this);
        closeMenu.setTextColor(Color.WHITE);
        closeMenu.setText(getString(R.string.contact_menu_close_menu));
        Drawable closeMenuIcon = getResources().getDrawable(R.drawable.menu_return);
        closeMenuIcon.setBounds(bounds);
        closeMenu.setCompoundDrawables(null, closeMenuIcon, null, null);
        closeMenu.setCompoundDrawablePadding(5);
        closeMenu.setTextSize(15);
        closeMenu.setId(R.drawable.menu_return);
        deleteAll.setPadding(20, 0, 20, 0);
        v.addView(closeMenu);

        builder.setView(v);

        return builder.create();
    }

    @Override
    protected void loadData() {
        menuTitles = getResources().getStringArray(R.array.contact_menu);
        TypedArray ta = getResources().obtainTypedArray(R.array.contact_menu_icon);
        menuIconsID = new int[ta.length()];
        for (int i = 0; i < menuIconsID.length; i++) {
            menuIconsID[i] = ta.getResourceId(i, 0);
        }
        ta.recycle();
        dialogLoading.show();

        new Thread(this).start();
    }

    @Override
    protected void event() {
        menu.setAdapter(menuAdapter);

        menu.setOnItemClickListener(this);

        search.addTextChangedListener(this);

        showAll.setOnClickListener(this);
        deleteAll.setOnClickListener(this);
        closeMenu.setOnClickListener(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_MENU) {
            menu.setVisibility(menu.isShown() ? View.GONE : View.VISIBLE);
            search.setVisibility(View.GONE);
        }
        return super.onKeyDown(keyCode, event);
    }

    private class MenuAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return menuIconsID.length;
        }

        @Override
        public String getItem(int position) {
            return menuTitles[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            TextView txt;
            if (convertView == null) {
                convertView = new TextView(ContactActivity.this);
            }
            txt = (TextView) convertView;
            txt.setText(menuTitles[position]);
            Drawable icon = getResources().getDrawable(menuIconsID[position]);
            icon.setBounds(0, 0, icon.getMinimumWidth(), icon.getMinimumHeight());
            txt.setCompoundDrawablesRelative(null, icon, null, null);
            txt.setGravity(Gravity.CENTER_HORIZONTAL);
            txt.setTextColor(Color.WHITE);
            return convertView;
        }

    }

    private class ContactsAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public ContactInfo getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Views v;
            if (convertView == null) {
                convertView = LayoutInflater.from(ContactActivity.this).inflate(R.layout.contact_item, parent, false);
                v = new Views(convertView);
                convertView.setTag(v);
            } else {
                v = (Views) convertView.getTag();
            }
            v.changeInfo(getItem(position));
            return convertView;
        }

        class Views implements OnClickListener {
            ImageView imgPhoto;
            TextView txtName;
            TextView txtPhone;

            ContactInfo info;

            Views(View v) {
                imgPhoto = (ImageView) v.findViewById(R.id.contact_photo);
                txtName = (TextView) v.findViewById(R.id.contact_name);
                txtPhone = (TextView) v.findViewById(R.id.contact_phone);

                v.findViewById(R.id.contact_call).setOnClickListener(this);
                v.findViewById(R.id.contact_msg).setOnClickListener(this);
                v.findViewById(R.id.contact_edit).setOnClickListener(this);
                v.setOnClickListener(this);

            }

            private void set() {
                imgPhoto.setImageDrawable(getResources().getDrawable(info.imageid));
                txtName.setText(info.getName());
                txtPhone.setText(info.getPhone());
            }

            public void changeInfo(ContactInfo item) {
                info = item;
                set();
            }

            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                case R.id.contact_call:
                    // 拨号
                    ContactActivity.this
                            .startActivity(new Intent(Intent.ACTION_CALL).setData(Uri.parse("tel:" + info.getPhone())));
                    break;
                case R.id.contact_msg:
                    // 进入短信界面 ，传入号码
                    ContactActivity.this.startActivity(new Intent(Intent.ACTION_VIEW).setType("vnd.android-dir/mms-sms")
                            .putExtra("address", info.getPhone()));
                    break;
                case R.id.contact_edit:
                    startActivityForResult(new Intent(ContactActivity.this, ContactInfoActivity.class)
                            .putExtra(CONTACTINFO, info).putExtra(REQUEST, REQUEST_CODE_EDIT), REQUEST_CODE_EDIT);
                    break;
                default:
                    startActivityForResult(new Intent(ContactActivity.this, ContactInfoActivity.class)
                            .putExtra(CONTACTINFO, info).putExtra(REQUEST, REQUEST_CODE_SHOW), REQUEST_CODE_SHOW);
                    break;
                }
            }
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        if (msg.what == 0) {
            dialogLoading.dismiss();

            empty.setVisibility(list.size() > 0 ? View.GONE : View.VISIBLE);

            contactsAdapter = new ContactsAdapter();
            contacts.setAdapter(contactsAdapter);
        }
        return false;
    }

    @Override
    public void run() {
        listAll = helper.query();
        list.clear();
        list.addAll(listAll);
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        handler.sendEmptyMessage(0);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (parent.getId() == menu.getId()) {
            switch (position) {
            case 0:// add
                Intent intent = new Intent(this, ContactInfoActivity.class);
                intent.putExtra(REQUEST, REQUEST_CODE_ADD);
                startActivityForResult(intent, REQUEST_CODE_ADD);
                break;
            case 1:// search
                search.setVisibility(search.isShown() ? View.GONE : View.VISIBLE);
                break;
            case 2:// menu
                dialogMenu.show();
                break;
            case 3: // exit
                finish();
                break;
            default:
                break;
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != ContactInfoActivity.RESULT_ADD && resultCode != ContactInfoActivity.RESULT_UPDATE) {
            return;
        }
        ContactInfo info = data.getParcelableExtra(ContactInfoActivity.BACK_RESULT);
        if (resultCode == ContactInfoActivity.RESULT_ADD) {
            list.add(info);
        } else {
            for (ContactInfo c : listAll) {
                if (c._id == info._id) {
                    c.setInfo(info);
                    break;
                }
            }
        }
        empty.setVisibility(list.size() > 0 ? View.GONE : View.VISIBLE);
        contactsAdapter.notifyDataSetChanged();
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        list.clear();
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        String str = s.toString();
        for (ContactInfo c : listAll) {
            if (c.findInfo(str))
                list.add(c);
        }
        empty.setVisibility(list.size() > 0 ? View.GONE : View.VISIBLE);
    }

    @Override
    public void afterTextChanged(Editable s) {
        contactsAdapter.notifyDataSetChanged();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.drawable.showall:
            search.setText("");
            list.clear();
            list.addAll(listAll);
            empty.setVisibility(list.size() > 0 ? View.GONE : View.VISIBLE);
            contactsAdapter.notifyDataSetChanged();
            break;
        case R.drawable.menu_delete1:
            new Builder(this).setTitle(getString(R.string.contact_menu_delete_all_sure))
                    .setIcon(R.drawable.menu_delete1).setMessage(R.string.contact_menu_delete_all_hint)
                    .setPositiveButton(getString(R.string.cancel), this).setNegativeButton(getString(R.string.ok), this)
                    .show();
            break;
        case R.drawable.menu_return:
            break;
        default:
            break;
        }
        dialogMenu.dismiss();
    }

    @Override
    public void onClick(DialogInterface dialog, int which) {
        if (which == DialogInterface.BUTTON_POSITIVE) {
            toast(getString(R.string.contact_menu_delete_all_cancel));
        } else {
            helper.delete();
            toast(getString(R.string.contact_menu_delete_all_deleted));
            list.clear();
            listAll.clear();
            empty.setVisibility(list.size() > 0 ? View.GONE : View.VISIBLE);
            contactsAdapter.notifyDataSetChanged();
        }
    }
}
